<?php
//ACTION SEND MESSAGE
function send_message(){

  global $CONFIG,$db,$err,$success;
  
  if($_POST["send_message"]){
      
	  $from_id = intval($_SESSION["login"]["id"]);
	  
	  $arr_to_id = array();
	  $arr_mail_user = array();
	  
	  $subject 		= strip_tags($_POST["subject"]);
	  $content 		= $_POST["content"];

	  if(!empty($_POST['to'])>0){
	  
			$username_arr	= explode(',',strip_tags($_POST['to']));
			
			for($i=0;$i<count($username_arr);$i++){
				
				$to_id = get_member_id(trim($username_arr[$i]));
				
				if($to_id==$from_id){
				    $err["to"] = "<font color='red'>[Bạn không thể gửi cho chính bạn].</font>";
					break;
				}
				
				if($to_id>0){

					if(is_guest(trim($username_arr[$i]))){  
						array_push($arr_mail_user,trim($username_arr[$i]));
					}
					
					array_push($arr_to_id,$to_id);
					
				}else{
					$err["to"] .= "<b>".trim($username_arr[$i])."</b><font color='red'> [không tồn tại]. </font>";
				}
			
			}
	  }else{
	  	$err["to"] = "<font color='red'>[Bạn chưa nhập người nhận].</font>";
	  }
  
	  if(empty($subject)){
	   
	     $err["subject"] = "<font color='red'>[Tiêu đề không được để trống].</font>";
	   
	  }
	  
	  if(empty($content)){
	  
	     $err["content"] = "<font color='red'>[Bạn chưa nhập nội dung].</font>";
	  }
	  
	  if(!$err){

		  $data = array();
		  
		  $data["from_id"] 		= $from_id;
		  $data["title"] 		= $subject;
	  	  $data["content"] 		= strip_tags($content,'<a><br><p><b><font><i><u><li><table><span><strong>');
		  $data["senddate"] 	= date('Y-m-d h:i:s',time());

		  
		  foreach($arr_mail_user as $value){
		  
		  	$to =  $value;
			
			send_mail($to,$from,$from_name="[Thành viên] ".$_SESSION["login"]["username"]." [trên] gtc.vn",$subject,$content);

		  }
		  
		  foreach($arr_to_id as $value){
		  
		  	$data["to_id"] 		=  $value;
			
		  	$insert = $db->exec_insert("member_message",$data); 
		  }

		  
	      if(mysql_affected_rows()>0){
		  		
			  $success = "<font color='green'>[Gửi thư thành công].</font>";
			  
			  unset($_POST);
		  }
	  }

  }

}
//GET INFO ID MEMBER THROUGH USERNAME
function get_member_id($username){

  global $db;

  $mem_rs = $db->query_first("SELECT mem_id FROM members WHERE username = '".mysql_real_escape_string($username)."' ");
  
  if($mem_rs['mem_id']<1){
  
  	return 0;
	
  }
  
  return $mem_rs['mem_id'];
  
}
//ACTION DELETE MESSAGE
function del_message(){
  
    global $db,$CONFIG_MEMBER_LINK;
    
	$user_id = intval($_SESSION["login"]["id"]);
	
  if($_POST){	
		if($_POST["mode"]=="sent"){
			
			$db->exec_update('member_message',array("del"=>'yes'),"`mes_id`=".intval($_POST["mes_id"])." AND from_id=".$user_id);
			
			server_redirect(get_link("member")."/".$CONFIG_MEMBER_LINK["sent"]);
		
		}else{
	   
			$db->exec_delete('member_message',"`mes_id`=".intval($_POST["mes_id"])." AND to_id=".$user_id);
			
			server_redirect(get_link("member")."/".$CONFIG_MEMBER_LINK["inbox"]);
		}
   }
}

//ACTION DEL MULTI USER
function del_multi_message($mode="inbox"){
  
  global $db;
  
  $user_id = intval($_SESSION["login"]["id"]);
  
  if($_POST){
  
  	   $arr_id = $_POST["check"];
       foreach($arr_id as $i=>$id){
	       if($mode=="sent"){
		   	$db->exec_update('member_message',array("del"=>'yes'),"`mes_id`=".intval($id)." AND from_id=".$user_id);
		   }else{
	   		$db->exec_delete('member_message',"`mes_id`=".intval($id)." AND to_id=".$user_id);
		   }
	   }
  }

}

function get_all_message_page($mode="inbox"){
   
    global $db,$CONFIG,$CONFIG_MEMBER_LINK,$params;

	$user_id = intval($_SESSION["login"]["id"]);

	if($mode=="sent"){
		
		$sel_all=$db->query_first("SELECT COUNT(mes_id) m FROM member_message WHERE from_id = ".$user_id." AND del='no'");
		
		$sql = "SELECT mm.*,mem.username FROM member_message as mm INNER JOIN members as mem ON mm.to_id = mem.mem_id WHERE mm.from_id = ".$user_id." AND del='no' ORDER BY mm.senddate DESC";
	
	}else if(is_numeric($mode)){
	
		$sel_all=$db->query_first("SELECT COUNT(mes_id) m FROM member_message WHERE to_id =".$user_id." AND property_id=".intval($mode));
		
		$sql = "SELECT mm.*,mem.username FROM member_message as mm INNER JOIN members as mem ON mm.from_id = mem.mem_id WHERE mm.to_id = ".$user_id." AND mm.property_id=".intval($mode)." ORDER BY mm.senddate DESC";
	
	}else{
	
		$sel_all=$db->query_first("SELECT COUNT(mes_id) m FROM member_message WHERE to_id =".$user_id);
		
		$sql = "SELECT mm.*,mem.username FROM member_message as mm INNER JOIN members as mem ON mm.from_id = mem.mem_id WHERE mm.to_id = ".$user_id." ORDER BY mm.senddate DESC";
		
	
	}
	
	$page=intval($params[count($params)-1]) ? intval($params[count($params)-1]) :1;
	$page=intval($page);
	if ($page<0) $page=1;
	$number=$sel_all['m']; 
	$limit = $CONFIG['rows_per_page_messages']; 
	$total=ceil($number/$limit); 
	$start = (($page*$limit)-$limit);
	
	$mess = $db->query($sql." LIMIT ".$start.",".$limit);
	//Xu ly ban ghi cuoi cung thi sap xep lai trang
	$rows = $db->num_rows($mess);
	if($page >1 && $rows<1)
	{
	   $page = $page -1;
	   
	   $total=ceil($number/$limit); 
	   $start = (($page*$limit)-$limit);
	
	   $mess = $db->query($sql." LIMIT ".$start.",".$limit);
	   
	   server_redirect(get_link("member")."/".$CONFIG_MEMBER_LINK[$mode]."/".$page);
	}
	
	if($start==0){$start=1;}
	if($page==1){$rows = $rows-1;}
	
	return array("message"=>$mess,"page"=>$page,"total"=>$total,"num_rows"=>$rows,"start"=>$start);

}

function get_noread_inbox($id){
  
  global $db;
  
  $result = $db->query_first("SELECT count(mes_id) as m FROM member_message WHERE to_id = ".intval($id)." AND `read`= 'No'");
  
  return intval($result["m"]);
}
function get_total_inbox($id){

  global $db;

  $result = $db->query_first("SELECT count(mes_id) as m FROM member_message WHERE to_id = ".intval($id));

  return intval($result["m"]);
}
function get_total_inbox_property($pid){
  
  global $db;
  
  $result = $db->query_first("SELECT count(mes_id) as m,max(from_id) as lastsend,max(mes_id) as lastid FROM member_message WHERE property_id = ".intval($pid));
  
  return $result;
}
function get_total_sent($id){
  
  global $db;
  
  $result = $db->query_first("SELECT count(mes_id) as m FROM member_message WHERE from_id = ".intval($id)." AND del='no'");
  
  return intval($result["m"]);
}
function read_message($mes_id){

  global $db,$mode;
   
    $mem_id = intval($_SESSION["login"]["id"]);
    
	$mode = "inbox"; 
	 
    $mes_view = $db->query_first("SELECT mm.*,mem.username,mem.email,mem.fullname FROM member_message as mm INNER JOIN members as mem ON mm.from_id = mem.mem_id WHERE mm.to_id = ".$mem_id." AND mm.mes_id=".intval($mes_id));
	
    if(!$mes_view){	  
	 
		 $mode = "sent"; 	   
		 $mes_view = $db->query_first("SELECT mm.*,mem.username,mem.email,mem.fullname FROM member_message as mm INNER JOIN members as mem ON mm.to_id = mem.mem_id WHERE mm.from_id = ".$mem_id." AND mm.mes_id=".intval($mes_id));
		
		 if(!$mes_view){echo "<font color=red>Thư này không tồn tại.</font>";die;}
	
	 }else{
		  //UPDATE READ FOR MESSAGE : ONLY READ INBOX - > UPDATE
		  $db->exec_update('member_message',array("`read`"=>"Yes"),'`mes_id`='.$mes_id);
	 }

	 
	 return $mes_view;
}
function is_guest($username){
  
  global $db;
  
  $result = $db->query_first("SELECT `type` FROM members WHERE username = '".mysql_real_escape_string($username)."'");
  
  if($result["type"]=="guest"){
    return true;
  }
  
  return false;
}
function id_read_next($mes_id,$mode,$pro_id=0){
		
	global $db;
		
	$mem_id = intval($_SESSION["login"]["id"]);
	
	if($mode=="sent"){
	 
		$mes_view = $db->query_first("SELECT mes_id FROM member_message WHERE from_id = ".$mem_id." AND mes_id > ".intval($mes_id)." ORDER BY mes_id ASC LIMIT 0,1");
	
	}else{
		
		if(intval($pro_id)>0){
			$add_con = " AND property_id=".intval($pro_id);
		}
		
		$mes_view = $db->query_first("SELECT mes_id FROM member_message WHERE to_id = ".$mem_id." AND mes_id > ".intval($mes_id).$add_con." ORDER BY mes_id ASC LIMIT 0,1");
	
    }
	 
	 return intval($mes_view["mes_id"]);
	
}
function id_read_back($mes_id,$mode,$pro_id=0){
		
	global $db;
		
	$mem_id = intval($_SESSION["login"]["id"]);
	
	if($mode=="sent"){
	 
		$mes_view = $db->query_first("SELECT mes_id FROM member_message WHERE from_id = ".$mem_id." AND mes_id < ".intval($mes_id)." ORDER BY mes_id DESC LIMIT 0,1");
	
	}else{
		
		if(intval($pro_id)>0){
			$add_con = " AND property_id=".intval($pro_id);
		}
		
		$mes_view = $db->query_first("SELECT mes_id FROM member_message WHERE to_id = ".$mem_id." AND mes_id < ".intval($mes_id).$add_con." ORDER BY mes_id DESC LIMIT 0,1");
	
    }
	 
	 return intval($mes_view["mes_id"]);
	
}
?>